import Mock from "mockjs"

/**
 * 操作成功
 */
export function success(data: any, code?: string, message?: string) {
    return Mock.mock({
        status: true,
        code,
        message: message ?? "操作成功",
        data
    })
}

/**
 * 操作失败
 */
export function error(code?: string, message?: string) {
    return Mock.mock({
        status: false,
        code,
        message: message ?? "操作失败"
    })
}

/**
 * 返回分页对象
 */
export function pagination<T = any>(pageNum: number, pageSize: number, data: T[]) {
    return success({
        pageNum,
        pageSize,
        totalRow: data.length + "",
        rows: currentPage(pageNum, pageSize, data)
    })
}

/**
 * 返回分页对象
 */
export function summaryPagination<T = any>(pageNum: number, pageSize: number, data: T[], summary: Recordable) {
    return success({
        pageNum,
        pageSize,
        totalRow: data.length + "",
        rows: currentPage(pageNum, pageSize, data),
        summary
    })
}

function currentPage<T = any>(pageNum: number, pageSize: number, data: T[]) {
    if (pageNum <= 0) {
        return []
    }
    const offset = (pageNum - 1) * pageSize
    return data.slice(offset, offset + pageSize)
}

/**
 * 对 callback 循环执行指定次数
 *
 * @param {Number} times 回调函数需要执行的次数
 * @param {Function} callback 回调函数
 */
export function doCustomTimes(times: number, callback: any) {
    let i = -1
    while (++i < times) {
        callback(i)
    }
}
